<template>
  <div class="app-container">
    <div class="execution-monitoring">
      <!-- 页面标题 -->
      <div class="page-header">
        <h2>执行日志监控</h2>
        <p>查看任务执行状态和日志详情</p>
      </div>

      <!-- 操作栏 -->
      <div class="operation-bar">
        <el-button type="primary" @click="refreshData">
          <i class="el-icon-refresh"></i>
          刷新
        </el-button>
        <el-button type="info" @click="exportLogs">
          <i class="el-icon-download"></i>
          导出日志
        </el-button>
      </div>

      <!-- 筛选条件 -->
      <div class="filter-bar">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="配置名称">
            <el-select v-model="filterForm.configId" placeholder="请选择配置" clearable size="small">
              <el-option
                v-for="config in configList"
                :key="config.id"
                :label="config.configName"
                :value="config.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="执行状态">
            <el-select v-model="filterForm.executeStatus" placeholder="请选择状态" clearable size="small">
              <el-option label="成功" value="SUCCESS"></el-option>
              <el-option label="失败" value="FAILED"></el-option>
              <el-option label="运行中" value="RUNNING"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="日期范围">
            <el-date-picker
              v-model="filterForm.dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              size="small"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="small" @click="searchLogs">查询</el-button>
            <el-button icon="el-icon-refresh" size="small" @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 执行日志表格 -->
      <div class="log-table">
        <el-table v-loading="loading" :data="logList" border style="width: 100%;">
          <el-table-column label="ID" prop="id" width="80"></el-table-column>
          <el-table-column label="配置名称" prop="configName" show-overflow-tooltip></el-table-column>
          <el-table-column label="执行时间" prop="executeTime" width="160">
            <template slot-scope="scope">
              {{ formatTime(scope.row.executeTime) }}
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="executeStatus" width="100">
            <template slot-scope="scope">
              <el-tag :type="getStatusTagType(scope.row.executeStatus)">
                {{ getStatusText(scope.row.executeStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="耗时(ms)" prop="executeDuration" width="100"></el-table-column>
          <el-table-column label="重试次数" prop="retryCount" width="80"></el-table-column>
          <el-table-column label="错误信息" prop="errorMessage" show-overflow-tooltip></el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="showLogDetail(scope.row)">详情</el-button>
              <el-button
                v-if="scope.row.executeStatus === 'FAILED'"
                type="text"
                size="small"
                @click="retryExecution(scope.row)"
              >重试</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            background
          ></el-pagination>
        </div>
      </div>

      <!-- 详情弹窗 -->
      <el-dialog
        title="执行日志详情"
        :visible.sync="detailDialogVisible"
        width="60%"
        append-to-body
      >
        <el-form label-width="100px" v-if="selectedLog">
          <el-form-item label="配置名称">
            <span>{{ selectedLog.configName }}</span>
          </el-form-item>
          <el-form-item label="执行时间">
            <span>{{ formatTime(selectedLog.executeTime) }}</span>
          </el-form-item>
          <el-form-item label="状态">
            <el-tag :type="getStatusTagType(selectedLog.executeStatus)">
              {{ getStatusText(selectedLog.executeStatus) }}
            </el-tag>
          </el-form-item>
          <el-form-item label="耗时(ms)">
            <span>{{ selectedLog.executeDuration }}</span>
          </el-form-item>
          <el-form-item label="重试次数">
            <span>{{ selectedLog.retryCount }}</span>
          </el-form-item>
          <el-form-item label="目标类">
            <span>{{ selectedLog.targetClass }}</span>
          </el-form-item>
          <el-form-item label="方法名">
            <span>{{ selectedLog.methodName }}</span>
          </el-form-item>
          <el-form-item label="方法参数">
            <pre class="json-content">{{ formatJson(selectedLog.methodParams) }}</pre>
          </el-form-item>
          <el-form-item label="执行结果">
            <pre class="json-content">{{ formatJson(selectedLog.resultData) }}</pre>
          </el-form-item>
          <el-form-item label="错误信息" v-if="selectedLog.errorMessage">
            <pre class="error-content">{{ selectedLog.errorMessage }}</pre>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关 闭</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getExecuteLogs,
  getConfigList,
  retryExecution
} from '@/api/assessAlert'

export default {
  name: 'ExecutionMonitoring',
  data() {
    return {
      loading: false,
      logList: [],
      configList: [],
      selectedLog: null,
      detailDialogVisible: false,
      filterForm: {
        configId: null,
        executeStatus: null,
        dateRange: null
      },
      pagination: {
        currentPage: 1,
        pageSize: 20,
        total: 0
      }
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    async loadData() {
      try {
        await Promise.all([
          this.loadConfigs(),
          this.loadLogs()
        ])
      } catch (error) {
        this.$message.error('加载数据失败: ' + error.message)
      }
    },
    async loadConfigs() {
      try {
        const response = await getConfigList({ page: 1, size: 1000 })
        if (response.code === 200) {
          this.configList = response.data.records || response.data
        } else {
          this.$message.error('获取配置列表失败: ' + response.msg)
        }
      } catch (error) {
        this.$message.error('获取配置列表失败: ' + error.message)
      }
    },
    async loadLogs() {
      this.loading = true
      try {
        const params = {
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize,
          configId: this.filterForm.configId,
          executeStatus: this.filterForm.executeStatus,
          beginTime: this.filterForm.dateRange ? this.filterForm.dateRange[0] : null,
          endTime: this.filterForm.dateRange ? this.filterForm.dateRange[1] : null
        }
        const response = await getExecuteLogs(params)
        if (response.code === 200) {
          this.logList = response.rows
          this.pagination.total = response.total
        } else {
          this.$message.error('加载执行日志失败: ' + response.msg)
        }
      } catch (error) {
        this.$message.error('加载执行日志失败: ' + error.message)
      } finally {
        this.loading = false
      }
    },
    searchLogs() {
      this.pagination.currentPage = 1
      this.loadLogs()
    },
    resetFilter() {
      this.filterForm = {
        configId: null,
        executeStatus: null,
        dateRange: null
      }
      this.pagination.currentPage = 1
      this.loadLogs()
    },
    refreshData() {
      this.loadData()
    },
    showLogDetail(row) {
      this.selectedLog = row
      this.detailDialogVisible = true
    },
    async retryExecution(row) {
      try {
        const response = await retryExecution(row.configId)
        if (response.code === 200) {
          this.$message.success('任务已提交重试')
          this.loadLogs()
        } else {
          this.$message.error('重试失败: ' + response.msg)
        }
      } catch (error) {
        this.$message.error('重试失败: ' + error.message)
      }
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.loadLogs()
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.loadLogs()
    },
    getStatusTagType(status) {
      switch (status) {
        case 'SUCCESS': return 'success'
        case 'FAILED': return 'danger'
        case 'RUNNING': return 'info'
        default: return 'info'
      }
    },
    getStatusText(status) {
      switch (status) {
        case 'SUCCESS': return '成功'
        case 'FAILED': return '失败'
        case 'RUNNING': return '运行中'
        default: return '未知'
      }
    },
    formatTime(time) {
      if (!time) return '-'
      return new Date(time).toLocaleString()
    },
    formatJson(jsonString) {
      if (!jsonString) return ''
      try {
        return JSON.stringify(JSON.parse(jsonString), null, 2)
      } catch (e) {
        return jsonString
      }
    },
    exportLogs() {
      this.$message.info('导出日志功能待实现')
    }
  }
}
</script>

<style scoped>
.execution-monitoring {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  color: #303133;
  margin-bottom: 10px;
}

.page-header p {
  color: #606266;
  font-size: 14px;
}

.operation-bar {
  margin-bottom: 20px;
}

.filter-bar {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-form {
  margin: 0;
}

.log-table {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.json-content {
  background: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  max-height: 200px;
  overflow-y: auto;
  font-size: 12px;
  line-height: 1.4;
}

.error-content {
  background: #fef0f0;
  color: #f56c6c;
  padding: 10px;
  border-radius: 4px;
  max-height: 200px;
  overflow-y: auto;
  font-size: 12px;
  line-height: 1.4;
}

.dialog-footer {
  text-align: right;
}
</style>
